package 哈希表;

public class HashBuckPlus <K,V>{
    public static class Node<K,V>{

        public K key;
        public V val;
        public Node<K,V> next;
        public Node(K k, V val) {
            this.key = k;
            this.val = val;
        }
    }
    public final double LOAD_FACTOR = 0.75;
    public Node<K,V>[]array;
    public int UsedSize;
    public HashBuckPlus() {
        array = (Node<K, V>[]) new Node[8];
    }
    public void put(K key,V val) {
        int index = key.hashCode() % array.length;
        Node<K,V> cur =array[index];
        while (cur != null) {
            //如果key相等就替换
            if(cur.key .equals(key)) {
                cur.val = val;
                return;
            }
            cur = cur.next;
        }
        //头插法进行插入
        Node<K,V> node = new Node<>(key,val);
        node.next = array[index];
        array[index] = node;
        UsedSize++;
        if(calculateLoadFactor() >= LOAD_FACTOR) {
            //扩容
            resize();
        }
    }
    //扩容
    private void resize() {
        //扩容需要注意什么？
        //每个元素都要重新的哈希
        Node<K,V>[] newArray =(Node<K,V>[])new Node[2*array.length];
        for (int i = 0; i < array.length; i++) {
            Node<K,V> cur = array[i];
            while (cur != null) {
                Node<K,V> curNext = cur.next;
                int index = cur.key.hashCode() % newArray.length;
                //头插
                cur.next = newArray[index];
                newArray[index] = cur;
                cur = curNext;
            }
        }
        array = newArray;
    }
    public V get(K key) {
        int index = key.hashCode() % array.length;
        Node<K,V> cur = array[index];
        while (cur != null) {
            if(cur.key .equals(key) ) {
                return cur.val;
            }
            cur = cur.next;
        }
        return null;
    }
    //计算负载因子
    public double calculateLoadFactor() {
        return UsedSize*1.0/array.length;
    }
}
